package com.dachuang.canjiren.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.dachuang.canjiren.entity.Register;
import com.dachuang.canjiren.entity.User;
import com.dachuang.canjiren.entity.UserRole;
import com.dachuang.canjiren.mapper.UserMapper;
import com.dachuang.canjiren.mapper.UserRoleMapper;
import com.dachuang.canjiren.service.RegisterService;
import com.dachuang.canjiren.utils.IDUtils;
import com.dachuang.common.utils.R;
import org.apache.ibatis.annotations.Param;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RequestMapping
@RestController
@CrossOrigin
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    StringEncryptor encryptor;

    @PostMapping("/pub/register")
    public R register(@Valid Register register){
        register.setActiveStatus(0);
        String activeCode = IDUtils.getUUID();
        register.setActiveCode(activeCode);
        String psw = register.getPassword();
        String spsw = encryptor.encrypt(psw);
        register.setPassword(spsw);
        boolean li = registerService.save(register);

        registerService.add(register);

        return R.ok().put("info",register);
    }

    /**
     *  校验激活码
     * @param code
     * @return
     */
    @GetMapping(value = "/pub/checkCode")
    public R checkCode(String code){

        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Register::getActiveCode,code);

        Register register = registerService.getOne(queryWrapper);
        //如果用户不等于null，把用户状态修改status=1
        if (register !=null){
            register.setActiveStatus(1);

            // 存入角色
            User users = userMapper.selectOne(new QueryWrapper<User>().eq("active_code",code));
            System.out.println(users);
            UserRole userRole = new UserRole();
            userRole.setUserId(users.getId());
            userRole.setRoleId(1);
            userRoleMapper.insert(userRole);

            //把code验证码清空，已经不需要了
            register.setActiveCode("");
            registerService.updateById(register);

            return R.ok();
        }

        return R.error();
    }

}
